<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/5/9
 * Time: 下午4:49
 */

namespace App\Busi\Modules\Resource;


use App\Busi\Modules\BaseBusi;
use App\Busi\Traits\UserTrait;
use App\Busi\Traits\VoucherTrait;
use App\Exceptions\ErrorCode\UserError;
use App\Exceptions\UserException;
use App\Http\Requests\PolicyListRo;
use App\Models\Policy;

class PolicyListBusi extends BaseBusi
{
    use UserTrait,VoucherTrait;
    public function handle(PolicyListRo $ro){
        $uid = $ro->uid;
        $user = $this->getUserByUid($uid);
        $num = 5;
        if(!$user){
            throw new UserException(UserError::USER_NOT_EXIST);
        }
        $id= $user['id'];
        $where = [
            ['user_id','=',$id]
        ];
        $fields = ['voucher_id','amount','created_at'];
        $data = Policy::where($where)->select($fields)->paginate($num);
        $total = $data->total();
        $pageNum =  ceil($total/$num);
        $ret = [];
        $ret["pageNum"] = $pageNum;

        $ret["currentPage"] = 0;
        $ret["balance"] = 0;
        $ret["used"] = 0;
        $ret["list"] = null;
        $policy = [];
        $balance = 0;
        $used = 0;
        $total = 0;
        if($data){
            $policy_item = [];
            foreach ($data as $item){
                $policy_item['name'] = $this->getVoucherNameByID($item['voucher_id']);
                $policy_item['create_time'] = substr($item['created_at'],0,10);
                $policy_item['amount'] = $this->getVoucherAmountByID($item['voucher_id']);
                $policy_item['balance'] = $item['amount'];
                array_push($policy,$policy_item);
                $balance = $balance+$item['amount'];
                $total = $total+$policy_item['amount'];

            }

        }
        $ret["currentPage"] = $data->currentPage();
        $ret["balance"] = $balance;
        $ret["used"] = $total-$balance;

        $ret["list"] = $policy;
        return $ret;

    }
}